<template>
  <div class='container'>
    <el-dialog @open="openFn" :title="form.id ? '修改信息' : '新增目录' " :visible="showDialog" width="40%" @close="close">
      <el-form :model="form" ref="form"  :rules="rules">
        <el-form-item v-if="showCard" label="所属学科" :label-width="formLabelWidth">
          <el-select v-model="form.subjectID" placeholder="请选择所属学科">
            <!-- <el-option :label="form.label" :value="form.value"></el-option> -->
            <el-option v-for="item in subjectList" :key="item.id" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录名称" :label-width="formLabelWidth" prop="directoryName">
          <el-input v-model="form.directoryName"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="addSubject">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { simple } from '@/api/hmmm/subjects'
import { add, update } from '@/api/hmmm/directorys'
export default {
  name: 'DirectorysAdd',
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    id: {
      type: String,
      default: null
    }
  },
  data () {
    return {
      form: {
        subjectID: '',
        directoryName: ''
      },
      rules: {
        directoryName: [
          { required: true, message: '目录名称不能为空' }
        ]
      },
      subjectList: [],
      formLabelWidth: '120px',
      showCard: true
    }
  },
  methods: {
    // 获取简单列表
    async getSubjectName () {
      const data = await simple()
      // console.log(data)
      this.subjectList = data.data
      // console.log(this.form)
    },
    close () {
      this.$emit('update:showDialog', false)
      this.$refs.form.resetFields()
      this.form = {
        subjectID: '',
        directoryName: ''
      }
    },
    // 新增目录+修改目录
    async addSubject () {
      // console.log(data)
      try {
        await this.$refs.form.validate()
      } catch {
        return
      }
      if (this.form.id) {
        await update({
          id: this.form.id,
          subjectID: this.form.subjectID || +this.id,
          directoryName: this.form.directoryName
        })
      } else {
        await add({
          subjectID: this.form.subjectID || +this.id,
          directoryName: this.form.directoryName
        })
      }
      this.$emit('update:showDialog', false)
      this.getList()
      this.$message.success('操作成功！')
    },
    getList () {
      this.$emit('getList')
    },
    showCardFn () {
      if (this.id) {
        this.showCard = false
      }
    },
    openFn () {
      this.showCardFn()
    }
  },
  created () {
    this.getSubjectName()
  }
}
</script>

<style scoped lang='less'>
  ::v-deep{
    .el-input__inner {
    width: 300px;
    }
  }
</style>
